package com.imooc.Controller;

import com.imooc.bean.Product;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author 14048
 * @Date 2022/1/13 15:09
 */
@RestController
@Slf4j
@RequestMapping("gateway")
public class GatewayController {

    public static final Map<Long, Product> items = new ConcurrentHashMap<>();


    @GetMapping("details")
    public Product get(
            @RequestParam("pid") Long pid) {
        if (!items.containsKey(pid)) {
            Product product = Product.builder().productId(pid)
                    .description("好吃不贵")
                    .stock(100L)
                    .build();
            items.putIfAbsent(pid, product);
        }

        return items.get(pid);
    }

    @PostMapping("placeOder")
    public String buy(@RequestParam("pid") Long pid) {
        Product product = items.get(pid);
        if (null == product) {
            return " product not found";
        } else if (product.getStock() <= 0) {
            return " Stock out";
        }

        synchronized (product) {
            if (product.getStock() <= 0) {
                return " Stock out";
            }

            product.setStock(product.getStock() - 1);

        }

        return "order placed";

    }

}
